package cn.china.xfood.controller;


import cn.china.xfood.service.MainService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import entity.Product;
import mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class MainController {

    @Autowired
    MainService mainService;

    @RequestMapping("selectByProductType")
    public List<String> selectByProductType(HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        List<String> list = mainService.selectAllType();


        return list;
    }

    @RequestMapping("selectByType")
    public List<Product> selectByType(HttpServletResponse res, @RequestParam String type, @RequestParam String currentPage) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        int i = Integer.parseInt(currentPage);
        List<Product> list = mainService.selectByType(type, i, 4);


        return list;

    }



    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("addCar")
    public String assCar(HttpServletResponse res, @RequestParam Integer id, @RequestParam String url, @RequestParam String name, @RequestParam Double price, @RequestParam String username) {
        res.setHeader("Access-Control-Allow-Origin", "*");

        List<Product> list = redisTemplate.opsForList().range(username, 0, redisTemplate.opsForList().size(username));

        redisTemplate.opsForList().getOperations().delete(username);

        for (int i = 0; i < list.size(); i++) {

            if (list.get(i).getId() == id) {

                Product p1 = list.get(i);
                p1.setProductAmount(p1.getProductAmount() + 1);
                list.remove(i);
                list.add(p1);
                redisTemplate.opsForList().leftPushAll(username, list);
                return "添加成功!";
            }
        }

        Product product = new Product(id, name, price, url);
        product.setProductAmount(1);
        list.add(product);
        redisTemplate.opsForList().leftPushAll(username, list);

        return "添加成功!";

    }

    @RequestMapping("getCar")
    public List<Product> getCar(HttpServletResponse res, @RequestParam String username) {
        res.setHeader("Access-Control-Allow-Origin", "*");

        List list = redisTemplate.opsForList().range(username, 0, redisTemplate.opsForList().size(username));

        return list;
    }


//    @RequestMapping("addProduct")
//    public String addProduct(HttpServletResponse res,@RequestParam("picID") MultipartFile file,@RequestParam String p_type, @RequestParam String p_name,@RequestParam String p_num,@RequestParam String price,@RequestParam String intro) throws IOException {
//        res.setHeader("Access-Control-Allow-Origin", "*");
//
//        InputStream ins = file.getInputStream();
//        byte[] bytes = new byte[65536];
//        String url = "F:/project/"+p_name+".png";
//        FileOutputStream out=new FileOutputStream(url);
//        StringBuffer sb=new StringBuffer();
//        int len=0;
//        while((len=ins.read(bytes))!=-1){
//            out.write(bytes, 0, len);
//        }
//
//        Product product = new Product(p_name, Double.parseDouble(price), Integer.parseInt(p_num), intro, 1.0, p_type, url);
//
//        int insert = mainService.insert(product);
//        if (insert>0){
//            return "添加成功!";
//        }else {
//            return "error";
//        }
//    }

    @RequestMapping(value = "/addProduct", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String upFile(@RequestParam("p_type") String p_type, @RequestParam("p_name") String p_name, @RequestParam("p_num") Integer p_num, @RequestParam("price") Double price, @RequestParam("intro") String intro, @RequestParam("picID") MultipartFile multipartFile, HttpServletResponse res) throws IOException {
        res.setHeader("Access-Control-Allow-Origin", "*");

        String realPath = ResourceUtils.getURL("classpath:").getPath();
        String originalFilename = multipartFile.getOriginalFilename();//获取图片原始的名称
        System.out.println("=======我上传的图片名称是:" + originalFilename);

        long l = System.currentTimeMillis();//获取当前毫秒数
        String newName = l + originalFilename;
        System.out.println("=======毫秒数+原始名称:" + newName);

        InputStream inputStream = multipartFile.getInputStream();//输入流,用来读取图片

        System.out.println("路径" + realPath);

//在项目根目录下创建image文件夹.用来保存上传的图片
        File file = new File(realPath + "/static/images/");
        if (!file.exists()) {
            file.mkdirs();//如果这个文件不存在,创建文件夹
        }


        if (!multipartFile.isEmpty()) {
            FileOutputStream fos = new FileOutputStream(realPath + "/static/images/" + newName);
            int length = 0;
            while ((length = inputStream.read()) != -1) {
                fos.write(length);
            }
            fos.flush();
            fos.close();
            inputStream.close();

        }

        String url = "http://localhost:8085/images/" + newName;
        Product product = new Product();
        product.setProductName(p_name);
        product.setProductAmount(p_num);
        product.setProductPrice(price);
        product.setProductType(p_type);
        product.setProductUrl(url);
        product.setProductIntroduce(intro);
        product.setProductDiscount(1.0);
        int i = mainService.insert(product);

        if (i > 0) {
            return "添加成功";
        } else {
            return "error";
        }


    }


    @RequestMapping("getAllPro")
    public List<Product> getAllPro(HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");

        return mainService.selectAllPro();
    }


    @RequestMapping("getCountByType")
    public int getCountByType(HttpServletResponse res, @RequestParam String type) {
        res.setHeader("Access-Control-Allow-Origin", "*");


        return mainService.selectCountByTypename(type);

    }


    @RequestMapping("getCountByTypeSSS")
    public int getCountByTypeSSS(HttpServletResponse res, @RequestBody Map<String,Object> map) {
        res.setHeader("Access-Control-Allow-Origin", "*");

        String type = (String)map.get("type");

        return mainService.selectCountByTypename(type);

    }

    /**
     * 调用别人的接口
     * @return
     */
    @RequestMapping("/myRestTemplate1")
    public String  myRestTemplate1(){

        RestTemplate rs = new RestTemplate();
        System.out.println(rs.getForObject("http://localhost:8085/getAllPro", List.class));

        return "";
    }


    /**
     * 带参数的接口调用
     * @return
     */
    @RequestMapping("/myRestTemplate2")
    public String  myRestTemplate2(){

        RestTemplate rs = new RestTemplate();


        Map<String,Object> map = new HashMap<>();
        map.put("type","hot");

        System.out.println(rs.postForObject("http://localhost:8085/getCountByTypeSSS", map,Integer.class));

        return "";
    }

    /**
     * 高德地图
     * @return
     */
    @RequestMapping("/addd")
    public String  myRestTemplate3(){

        RestTemplate rs = new RestTemplate();

        JSONObject forObject = rs.getForObject("http://restapi.amap.com/v3/ip?key=50f24136d679fa4b821e892746c89e9e", JSONObject.class);

        System.out.println(forObject);

        return "";

    }







//    @RequestMapping("selectAllProduct")
//    public List<Product> selectAllProduct(HttpServletResponse res,@RequestParam String currentPage ) {
//        res.setHeader("Access-Control-Allow-Origin", "*");
//
//        int i = Integer.parseInt(currentPage);
//
//        return mainService.selectAllProduct(i,4);
//    }





    @RequestMapping("offProduct")
    public String offProduct(HttpServletResponse res,@RequestParam int id) {
        res.setHeader("Access-Control-Allow-Origin", "*");

        int i = mainService.deleteByPrimaryKey(id);
        if (i>0){
            return "下架成功";
        }else {
            return "网络繁忙...";
        }

    }




}